In [1]:
%matplotlib inline
In [2]:
import brightway2 as bw
import presamples
import numpy as np
import matplotlib.pyplot as plt
Create a new project for this demonstration notebook
In [3]:
bw.projects.set_current("parameterized presamples example")
Need basic migrations for Excel notebook importer
In [4]:
bw.create_core_migrations()
Import a simple parameterized system; you can find the Excel workbook in the same directory as this notebook.
In [5]:
e = bw.ExcelImporter("parameterized.xlsx")
e.apply_strategies()
# This database is very simple, matching by name is already enough
e.match_database(fields=["name"])
e.statistics()
Out[5]:
In [6]:
e.write_database()
Check to make sure our parameters were imported correctly; should have 4 parameters.
In [7]:
bw.parameters
Out[7]:
Define a toy LCIA method
In [8]:
a_method = bw.Method(("a method",))
In [9]:
a_method.register()
a_method.write([(("stuffy", "silly"), 1)])
We now need to use one of the predefined models in the presamples library to generated Monte Carlo sampled values from these parameters. We have four parameters; two are uncertain variables, and two are the calculated using formulas.
Everything we need is already in the database, but we need to tell the model the name of the group of parameters to work with. This model is generalized to work with preexisting presampled values and multiple groups, but in this case we only have one named group (defined in the Excel workbook).
In [10]:
from presamples.models import ParameterizedBrightwayModel
In [11]:
model = ParameterizedBrightwayModel("teddy_bears") # Name of parameter group
model.load_parameter_data() # Load data from parameters database
model.calculate_stochastic(iterations=1000, update_amounts=True) # 1000 Monte Carlo iterations; keep results
model.calculate_matrix_presamples() # Transform results to be useful in LCA calculations
_, filepath = model.save_presample("fidget") # Name of new presample package
Our presamples package is a new directory; presample packages are described in the library documentation.
In [12]:
filepath
Out[12]:
In [13]:
lca = bw.LCA({("stuffy", "widget"): 1}, a_method.name)
lca.lci()
lca.lcia()
lca.score
Out[13]:
Monte Carlo without the presampled values has no uncertainty
In [20]:
mc = bw.MonteCarloLCA({("stuffy", "widget"): 1}, a_method.name)
results = [next(mc) for _ in range(1000)]
plt.hist(results, histtype='step')
Out[20]:
Using presampled values introduces uncertainty from the uncertain variables, and chain of formulas
In [21]:
mc = bw.MonteCarloLCA({("stuffy", "widget"): 1}, a_method.name, presamples=[filepath])
results = [next(mc) for _ in range(1000)]
plt.hist(results, histtype="step")
Out[21]:
In [ ]: